package com.hethongviet.vending.pages;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.hethongviet.vending.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.bluetooth.BluetoothUtil;
import com.hethongviet.vending.bluetooth.OnBluetoothListener;
import com.hethongviet.vending.helper.GeneralActivity;
import com.hethongviet.vending.helper.call.ListenPhoneCallService;
import com.hethongviet.vending.helper.db.AccountSQLite;
import com.hethongviet.vending.helper.db.BoxSQLite;
import com.hethongviet.vending.helper.db.MachineSQLite;
import com.hethongviet.vending.helper.db.ProductSQLite;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.model.Account;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.MachineInfo;
import com.hethongviet.vending.model.Product;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.CONSTANTS.SERVICE;

public class StandbyActivityNonBluetooth extends GeneralActivity
		implements OnBluetoothListener
{
	private static final int REQUEST_ENABLE_BT = 1;

	private Button _buttonLoginUser = null;
	private Button _buttonLoginService = null;
	private ViewGroup _layoutBG = null;
	private static final int TOTAL_DRAWABLES = 3;
	private int[] _drawable = new int[TOTAL_DRAWABLES];
	private int _drawableIndex = 0;

	private Timer _timerAdvertisement = null;

	private Timer _timerUpdateData = null;

	private AccountSQLite _accountSqLite = new AccountSQLite(this);
	private MachineSQLite _machineSqLite = new MachineSQLite(this);
	private BoxSQLite _boxSqLite = new BoxSQLite(this);
	private ProductSQLite _productSqLite = new ProductSQLite(this);

	public StandbyActivityNonBluetooth()
	{
		_accountSqLite = new AccountSQLite(this);
		_machineSqLite = new MachineSQLite(this);
		_boxSqLite = new BoxSQLite(this);
		_productSqLite = new ProductSQLite(this);
	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_standby);

		if (!AppConfig.IS_NETWORK_AVAILABLE)
		{
			// Create Database
			_accountSqLite = new AccountSQLite(this);
			_boxSqLite = new BoxSQLite(this);
			_productSqLite = new ProductSQLite(this);

			List<Box> boxsList = null;
			try
			{
				boxsList = _boxSqLite.getAll();
			} catch (Exception e)
			{
				e.printStackTrace();
				boxsList = null;

			}

			if (boxsList == null || boxsList.size() == 0)
			{
				// if (!_accountSqLite.isTableExist())
				{
					// _accountSqLite.deleteAll();

					_accountSqLite.insert(new Account("0937813357",
							"Dinh Thi Duyen", 0, 0, Account.PERMIT_USER, false,
							"", true, System.currentTimeMillis(), "", "bkit05",
							"ngoctan", 0));
					_accountSqLite.insert(new Account("0942478466",
							"Dinh Ngoc Tan", 0, 0, Account.PERMIT_USER, false,
							"", true, System.currentTimeMillis(), "", "duyen",
							"duyen", 0));
					_accountSqLite.insert(new Account("0975992243",
							"Dinh Thi Duyen", 0, 0, Account.PERMIT_USER, false,
							"", true, System.currentTimeMillis(), "", "duyen",
							"duyen", 0));
					_accountSqLite.insert(new Account("0903946510",
							"Nguyen Chien Thang", 0, 0, Account.PERMIT_ADMIN,
							false, "", true, System.currentTimeMillis(), "",
							"thang", "thang", 0));

				}
				// if (!AppMain.getInstance()._machineInfoSqLite.isTableExist())
				{
					// AppMain.getInstance()._machineInfoSqLite.deleteAll();

					// HTC One V
					MachineInfo machine = new MachineInfo("01645401194", 40,
							System.currentTimeMillis(), 0, 15, 342142142.23423,
							0, 234242.23423, "0975075350", "", "0975075350", 1,
							1, "0975075350", "1C:B0:94:6E:B8:93",
							"00:12:03:09:14:98", "http://localhost", 1234);

					// LG P350
					machine = new MachineInfo("01645401194", 40,
							System.currentTimeMillis(), 0, 15, 342142142.23423,
							0, 234242.23423, "0975075350", "", "0975075350", 1,
							1, "0975075350", "38:EC:E4:BA:E1:33",
							"00:12:03:09:14:98", "http://localhost", 1234);

					_machineSqLite.insert(machine);
				}

				// if (!_productSqLite.isTableExist())
				{
					// _productSqLite.deleteAll();
					_productSqLite.insert(new Product("PEPSI", "K0", 0, 5000,
							"Hang chat luong cao", ""));
					_productSqLite.insert(new Product("AQUAFINA", "K1", 0,
							5000, "Hang chat luong cao", ""));
					_productSqLite.insert(new Product("STING", "K2", 0, 8000,
							"Hang chat luong cao", ""));
					_productSqLite.insert(new Product("YELLOW STING", "K3", 0,
							9000, "Hang chat luong cao", ""));
					_productSqLite.insert(new Product("SEVENUP", "K4", 0, 8000,
							"Hang chat luong cao", ""));
					_productSqLite.insert(new Product("REVIVE", "K5", 0, 8000,
							"Hang chat luong cao", ""));
					_productSqLite.insert(new Product("TWISTER", "K6", 0, 9000,
							"Hang chat luong cao", ""));
					_productSqLite.insert(new Product("MIRINDA CAM", "K7", 0,
							8000, "Hang chat luong cao", ""));
					_productSqLite.insert(new Product("MIRINDA XA XI", "K8", 0,
							9000, "Hang chat luong cao", ""));
					_productSqLite.insert(new Product("COCA COLA", "K9", 0,
							5000, "Hang chat luong cao", ""));
					_productSqLite.insert(new Product("LAVIE", "K10", 0, 5000,
							"Hang chat luong cao", ""));
					_productSqLite.insert(new Product("C2", "K11", 0, 5000,
							"Hang chat luong cao", ""));
				}
				// if (!_boxSqLite.isTableExist())
				{
					// _boxSqLite.deleteAll();
					_boxSqLite.insert(new Box(0, "00", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(1, "01", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(2, "02", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(3, "03", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(4, "04", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(5, "05", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(6, "06", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(7, "07", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(8, "08", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(9, "09", "", 0, 0, 0, "", 1));

					_boxSqLite.insert(new Box(10, "10", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(11, "11", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(12, "12", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(13, "13", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(14, "14", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(15, "15", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(16, "16", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(17, "17", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(18, "18", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(19, "19", "", 0, 0, 0, "", 1));

					_boxSqLite.insert(new Box(20, "20", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(21, "21", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(22, "22", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(23, "23", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(24, "24", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(25, "25", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(26, "26", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(27, "27", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(28, "28", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(29, "29", "", 0, 0, 0, "", 1));

					_boxSqLite.insert(new Box(30, "30", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(31, "31", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(32, "32", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(33, "33", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(34, "34", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(35, "35", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(36, "36", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(37, "37", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(38, "38", "", 0, 0, 0, "", 1));
					_boxSqLite.insert(new Box(39, "39", "", 0, 0, 0, "", 1));

				}
			}
		}

		_buttonLoginUser = (Button) findViewById(R.id.button_login_user);
		_buttonLoginService = (Button) findViewById(R.id.button_login_service);

		if (AppConfig.IS_DEBUG)
		{
			// AppMain.getInstance()._machineInfo = new MachineInfo("VM01", "01645401194", 40,
			// "5C:17:D3:9B:2E:76", "00:12:03:09:14:98");//LG P350

			_buttonLoginUser.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0)
				{
					if (BluetoothUtil.isConnected())
					{
						Utils.debug("Bluetooth is not available!");
						if (AppConfig.IS_DEBUG)
							showDialog(R.string.message_bluetooth_not_available);
						return;
					}

					AppMain.getInstance().setCurrentAccount(_accountSqLite.getById("0942478466"));
					Utils.debug("get account="
							+ AppMain.getInstance().getCurrentAccount().getId());

					Intent intent = new Intent(
							StandbyActivityNonBluetooth.this,
							UserActivity.class);
					startActivity(intent);
				}
			});

			_buttonLoginService.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0)
				{
					AppMain.getInstance().setCurrentAccount(_accountSqLite.getById("0942478466"));
					Utils.debug("get account="
							+ AppMain.getInstance().getCurrentAccount().getId());

					Intent intent = new Intent(
							StandbyActivityNonBluetooth.this,
							ServiceModeActivity.class);
					startActivity(intent);
				}
			});
		}
		else
		{
			_buttonLoginService.setVisibility(View.GONE);
			_buttonLoginUser.setVisibility(View.GONE);
		}

		_drawable[0] = R.drawable.ad1;
		_drawable[1] = R.drawable.ad2;
		_drawable[2] = R.drawable.ad3;

		_layoutBG = (RelativeLayout) findViewById(R.id.background);

		TimerTask timerTask = new TimerTask() {

			@Override
			public void run()
			{
				onUpdateAdvertisement();
			}
		};

		_timerAdvertisement = new Timer();
		_timerAdvertisement.scheduleAtFixedRate(timerTask, 0, Constant.TIME_ADVERTISEMENT_STEP);

		TimerTask timerTaskUpdateData = new TimerTask() {

			@Override
			public void run()
			{
				// Intent intent = new Intent(StandbyActivity.this,
				// PauseActivity.class);
				// intent.putExtra(PauseActivity.EXTRA_REQUEST_TYPE,
				// MAIN_CONFIG.MACHINE_REQUEST_UPDATE_DATA);
				// startActivity(intent);
			}
		};

		_timerUpdateData = new Timer();
		_timerUpdateData.schedule(timerTaskUpdateData, Constant.TIME_UPDATE_DATA);

	}

	//
	// @Override
	// public void onAttachedToWindow() {
	// this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	// super.onAttachedToWindow();
	// }

	@Override
	public void onStart()
	{
		super.onStart();
		//
		// // If BT is not on, request that it be enabled.
		// // setupChat() will then be called during onActivityResult
		// if (_bluetoothAdapter != null && !_bluetoothAdapter.isEnabled())
		// {
		// Intent enableIntent = new Intent(
		// BluetoothAdapter.ACTION_REQUEST_ENABLE);
		// startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		// // Otherwise, setup the chat session
		// }
	}

	@Override
	protected void onResume()
	{
		AppMain.getInstance().setStandbyScreen(true);
		BluetoothUtil.start();
		BluetoothUtil.setListener(this);
		super.onResume();
	}

	@Override
	protected void onStop()
	{
		AppMain.getInstance().setStandbyScreen(false);
		super.onStop();
	}

	@Override
	protected void onDestroy()
	{
		Utils.debug("Standby activity ------------ destroy");

		BluetoothUtil.stop();

		stopService(new Intent(this, ListenPhoneCallService.class));

		super.onDestroy();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	public void processCellPhoneNumber(String cellPhoneIncom)
	{
		List<Account> accounts = _accountSqLite.getAll();

		for (Account account : accounts)
		{
			if (cellPhoneIncom.equals(account.getId()))
			{
				final int permitAccess = account.getPermitAccess();
				AppMain.getInstance().setCurrentAccount(account);

				// AppMain.getInstance().showAlert(this,
				// _instance.getString(R.string.welcome_user));
				//
				//
				// try
				// {
				// Thread.sleep(1000);
				// } catch (InterruptedException e)
				// {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }

				// new CountDownTimer(2000, 2000) {
				//
				// @Override
				// public void onTick(long arg0)
				// {
				// }
				//
				// @Override
				// public void onFinish()
				// {

				if (permitAccess == Account.PERMIT_ADMIN)
				{

				}
				else if (permitAccess == Account.PERMIT_OPERATOR)
				{
					Intent intent = new Intent(this, ServiceModeActivity.class);
					startActivity(intent);
				}
				else
				// if (permitAccess == Account.PERMIT_USER))
				{
					Intent intent = new Intent(this, UserActivity.class);
					startActivity(intent);
				}
				// }
				// }.start();

				return;
			}
		}

		/* Not registering */
		showDialog(R.string.message_user_not_egister);

	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_user_not_egister)
		{
			return new DialogMessageBack(this, false, id, false);
		}
		else if (id == R.string.message_bluetooth_not_available)
		{
			return new DialogMessageBack(this, true, id, false);
		}
		else
			return super.onCreateDialog(id);
	}

	private void onUpdateAdvertisement()
	{
		this.runOnUiThread(new Runnable() {

			@Override
			public void run()
			{
				_layoutBG.setBackgroundDrawable(getResources().getDrawable(_drawable[_drawableIndex++]));
				_drawableIndex = (_drawableIndex == TOTAL_DRAWABLES) ? 0
						: _drawableIndex;
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case REQUEST_ENABLE_BT:
				// When the request to enable Bluetooth returns
				if (resultCode != Activity.RESULT_OK)
				{
					// User did not enable Bluetooth or an error occured
					if (AppConfig.IS_DEBUG)
					{
						Utils.debug("******** Bluetooth is not open!");
						Toast.makeText(this, "******** Bluetooth is not open!", Toast.LENGTH_SHORT).show();
					}
					finish();
				}
		}
	}

	@Override
	public void onBluetoothInComingMessage(String Message)
	{
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{
		if (transaction == null)
		{
			Utils.debug("Null -----------received");
			return;
		}

		String message = transaction.getMessageReceived();
		Utils.debug("Receive message = " + message);

		if (message.equalsIgnoreCase(SERVICE.RESULT_OK))
		{
			Utils.debug("OK!!!!!!!!!!!");
			hideProgressDialog();

			return;
		}

	}

	@Override
	public void onConnectFail(int typeError)
	{

		Utils.debug("Connect fail!.......................");
		hideProgressDialog();

		showDialogWithStatus(typeError);
	}
}
